<template>
  <div class="item">
<!--    <el-button @click="exist" >注销登录</el-button>-->
    <div  style="float: right;margin: 20px">
      <el-button @click="ToLogout" v-if="role!==''&&role!==null&&role!==undefined">注销</el-button>
      <el-button  @click="ToLogin" v-else>登录  |  注册</el-button>
    </div>
    <el-button @click="toHome" style="float: right;margin: 20px">返回首页</el-button>
    <el-form ref="form" :model="form" label-width="80px" style="padding-top: 100px">
      <el-form-item label="昵称">
        <el-input :value="userName" style="width: 40%"></el-input>
      </el-form-item>
      <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action = "action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl !== ''" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
      </el-form-item>
      <el-form-item label="性别" v-if="radio !== '1'">
        <el-radio v-model="radio" label="女">女</el-radio>
        <el-radio v-model="radio" label="男">男</el-radio>
      </el-form-item>
      <el-form-item>
        <el-button type="info" @click="editInfo">修改个人信息</el-button>
      </el-form-item>
      <el-form-item label="密码">
        <el-button type="warning" @click="resetPass">修改密码</el-button>
      </el-form-item>

      <el-form-item label="详细信息">
        <el-button v-if="borrow" type="primary" @click="displayBorrow=true">借阅记录</el-button>
        <el-button v-if="reserveBook" type="primary" @click="displayReserveBook=true">借阅预定</el-button>
        <el-button v-if="overdue" type="primary" @click="displayOverdueData=true">逾期记录记录</el-button>
      </el-form-item>

      <!--借阅记录-->
      <el-dialog title="用户信息" :visible.sync="displayBorrow" class="dialog">
        <el-table
                  :data="borrowData"
                  style="width: 70%;">
          <el-table-column
            prop="book.bName"
            label="书名">
          </el-table-column>
          <el-table-column
            prop="book.bAuthor"
            label="作者">
          </el-table-column>
          <el-table-column
            prop="book.bPublish"
            label="出版社">
          </el-table-column>
          <el-table-column
            prop="lendTime"
            label="借阅实践"
            width="180">
          </el-table-column>
          <el-table-column
            prop="backTime"
            label="截止时间"
            width="180">
          </el-table-column>
        </el-table>
      </el-dialog>

      <!--借阅预定-->
      <el-dialog title="用户信息" :visible.sync="displayReserveBook" class="dialog">
        <el-table :data="reserveData" style="width: 80%;">
          <el-table-column
            prop="book"
            label="预定书名">
          </el-table-column>
          <el-table-column
            prop="startTime"
            label="预定时间">
          </el-table-column>
          <el-table-column
            prop="lastTime"
            label="预定截至时间">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="props">
              <el-button @click="userReserveCancel(props.row)">取消预定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

      <!--逾期记录-->
      <el-dialog title="用户信息" :visible.sync="displayOverdueData" class="dialog">
        <el-table
                  :data="overdueData"
                  style="width: 70%;">
          <el-table-column
            prop="book.bName"
            label="书名">
          </el-table-column>
          <el-table-column
            prop="book.bAuthor"
            label="作者">
          </el-table-column>
          <el-table-column
            prop="book.bPublish"
            label="出版社">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="props">
              <el-button @click="backOverdue(props.row)">逾期归还</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>

    </el-form>

    <!--修改密码的对话框-->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="旧密码" prop="oldPass">
          <el-input type="password" v-model="ruleForm.oldPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="pass">
          <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkPass">
          <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { getUserInfo,
    getBasicInfo,
    userPasswordEdit,
    adminPasswordEdit,
    editUserBasicInfo,
    editAdminBasicInfo,
    userCover,
    userOverdue,
    userBorrowInfo,
    userBookInfo,
    userCancelReserve,
    backOverdueBook
  } from "../../api/list"
  import {
    getuserName,
    getRole,
    removeAccessToken,
    removeRole,
    removeuserName
  } from "../../utils/cacheProcessing"
  export default {
    name:"user",
    data () {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        id:"",
        radio: '1',
        displayOverdueData:false,
        displayBorrow:false,
        displayReserveBook:false,
        borrow:false,
        reserveBook:false,
        overdue:false,
        userName:"123",
        imageUrl:"",
        action:"",
        pageNum:1,
        overdueData:{

        },
        form: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: '',
          imageUrl: 'http://47.115.62.124:8080/img/headImg.jpg'
        },
        dialogFormVisible: false,
        ruleForm: {
          oldPass:"",
          pass: '',
          checkPass: '',
        },
        rules: {
          oldPass: [
            { request: true, message: "请输入密码",trigger: 'blur' }
          ],
          pass: [
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
        borrowData: [],
        reserveData:[],
          role:getRole()
      }
    },
    components: {
    },
    created(){
      this.GetUserInfo();
      if(getRole()==='ROLE_USER'){
        this.reserveBook = this.borrow = true
      }
    },
    mounted(){
      this.GetUserInfo();
      if(getRole()==='ROLE_USER'){
        this.reserveBook = this.borrow = true
      }
    },
    computed: {
    },
    methods: {
      /*页面初始化加载信息*/
      GetUserInfo(){
        let requestData = {
          username: getuserName()
        }
        if(getRole()==="ROLE_ADMIN"){
          getBasicInfo(requestData).then(res=>{
            this.imageUrl = 'http://47.115.62.124:8080/img/'+res.data.data.imgUrl
            this.id=res.data.data.id;
            this.userName = getuserName()
          }).catch(err=>{

          })
        }else{
          getUserInfo(requestData).then(res=>{
            this.imageUrl = 'http://47.115.62.124:8080/img/'+res.data.data.uImg
            this.radio = res.data.data.uSex;
            this.userName = getuserName()
            this.id = res.data.data.uId;

            /*借阅记录的获取*/
            let data = {
              pageNum:this.pageNum,
              userId:this.id,
            }
            userBorrowInfo(data).then(res=>{
                 this.borrowData = res.data.data
                 this.borrow = true
            }).catch(err=>{

            })
            data = {
              userId:this.id
            }
            /*预定记录获取*/
            userBookInfo(data).then(res=>{
            //  console.log(res);
              this.reserveBook = true
              this.reserveData = res.data.data;
            }).catch(err=>{

            })
            /*逾期记录获取*/
            userOverdue(data).then(res=>{
           //   console.log(res);
              this.overdue = true
              this.overdueData = res.data.data;
            }).catch(err=>{

            })
          }).catch(err=>{

          });

        }
      },
      toHome(){
        this.$router.push('/home')
      },
      /*取消预定*/
      userReserveCancel(book){
        this.confirm({
          content: "确定取消该图书的预定?",
          fn: ()=>{
            let requestData = {
              userId:this.id,
              bookId:book.bookId,
            }
            userCancelReserve(requestData).then(res=>{
              this.$messageOK("success","取消预定成功")
              this.getUserInfo()
            })
          },
          catchfn: () => {
            this.$messageOK("warning","取消预定失败")
          }
        });
      },
      /*逾期归还*/
      backOverdue(book){
        this.confirm({
          content: "确定归还该图书?",
          fn: ()=>{
            let requestData = {
              userId:this.id,
              bookId:book.bookId,
            }
            backOverdueBook(requestData).then(res=>{
              this.$messageOK("success","归还成功")
              this.getUserInfo()
            })
          },
          catchfn: () => {
            this.$messageOK("warning","归还失败")
          }
        });
      },
        //进入登录界面
        ToLogin(){
            this.$router.push('/login')
        },
        /*退出个人中心*/
        ToLogout(){
            this.confirm({
                content: "此操作将注销当前登录用户，是否继续?",
                fn: ()=>{
                    console.log("hi")
                    removeAccessToken()
                    removeRole()
                    removeuserName()
                    this.$router.push('/login')
                },
                catchfn: () => {
                }
            });

        },
      /*修改用户头像*/
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      /*上传前的校验*/
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        let requestData = {
          username:getuserName(),
          file:file
        }
        if(this.userName === "ROLE_ADMIN"){
          userAdmin(requestData).then(res=>{
            this.$messageOK("success", "修改头像成功");
            this.getUserInfo()
            this.dialogFormVisible = false;
          }).catch(err=>{
            this.$messageOK("warning", "修改头像失败！");
          })
        }else{
          userCover(requestData).then(res=>{
            this.$messageOK("success", "修改头像成功！");
            this.getUserInfo()
          }).catch(err=>{
            this.$messageOK("warning", "修改头像失败！");
          })
        }
        return isJPG && isLt2M;
      },
      /*修改密码上传*/
      submitForm(formName) {
        this.confirm({
          content: "确认修改密码?",
          fn: this.changePass,
          catchfn: () => {
            this.$messageOK("warning", "修改密码失败！");
          }
        });
      },
      /*修改密码*/
      changePass(){
        let requestData = {
          userId:this.id,
          oldPassword:this.ruleForm.oldPass,
          newPassword:this.ruleForm.checkPass
        }
        if(this.userName !== "ROLE_ADMIN"){
            userPasswordEdit(requestData).then(res=>{
              this.$messageOK("success", "修改密码成功！");
              this.dialogFormVisible = false;
          }).catch(err=>{
              this.$messageOK("warning", "修改密码失败！");
          })
        }else{
          adminPasswordEdit(requestData).then(res=>{
            this.$messageOK("success", "修改密码成功！");
          }).catch(err=>{
            this.$messageOK("warning", "修改密码失败！");
          })
        }
      },
      /*重置修改密码页面*/
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      /*重置修改密码页面*/
      resetPass(){
        this.dialogFormVisible = true;
        this.ruleForm.oldPass = this.ruleForm.pass = this.ruleForm.checkPass =''
      },
      editInfo(){
        this.confirm({
          content: "确认修改个人信息?",
          fn: this.changeInfo,
          catchfn: () => {
            this.$messageOK("warning", "修改个人信息失败！");
          }
        });
      },
      /*修改个人信息*/
      changeInfo(){
        /*修改管理员个人信息*/
        if(getRole() === "ROLE_ADMIN"){
          let requestData={
            id:this.id,
            name: this.userName,
          }
          editAdminBasicInfo(requestData).then(res=>{
            this.$messageOK("success", "修改个人信息成功");
            this.GetUserInfo();
          }).catch(err=>{
            this.$messageOK("warning", "修改个人信息失败！");
          })
          /*修改普通用户的个人信息*/
        }else{
          let requestData={
            uId:this.id,
            uName: this.userName,
            uSex: this.radio
          }
          editUserBasicInfo(requestData).then(res=>{
            this.$messageOK("success", "修改个人信息成功");
            this.GetUserInfo();
          }).catch(err=>{
            this.$messageOK("warning", "修改个人信息失败！");
          })
        }
      }
    },
  }
</script>

<style lang="scss" scoped>
  .item{
    height: 100%;
    width: 100%;
    padding-left: 150px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-table{
    margin: auto;
  }
</style>
